/**
 * 
 */
package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StrictMode;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;

/**
 * @author ZJJ
 */
public class Pswmodify extends Activity
{

	private Pswmodify oThis = this;
	private EditText username, oldpassword, password, repassword, phoneno;
	private Button saveButton;
	private ImageButton cancelButton;
	private ProgressDialog proDialog;
	InputMethodManager manager;
	MyApplication myApplication;
	private static final int LOADUSERSUCC = 1;
	private static final int LOADUSERERR = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
				.detectNetwork() // or .detectAll() for all detectable problems
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog()
				.penaltyDeath().build());
		setContentView(R.layout.pswmodify);
		myApplication = (MyApplication) getApplication();
		findViews();
		setListeners();
		new Thread(new InitUser()).start();
	}

	private void findViews()
	{
		// manager = (InputMethodManager)
		// getSystemService(Context.INPUT_METHOD_SERVICE);

		// 得到相应的显示控件的对象
		username = (EditText) findViewById(R.id.username);
		// username.setText(myApplication.getAccount());
		// username.setEnabled(false);
		oldpassword = (EditText) findViewById(R.id.oldpassword);
		password = (EditText) findViewById(R.id.password);
		repassword = (EditText) findViewById(R.id.repassword);
		phoneno = (EditText) findViewById(R.id.phoneno);
		// phoneno.setText(myApplication.getSjh());
		// phoneno.setEnabled(false);
		// username.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		// password.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		// repassword.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		// phoneno.setOnFocusChangeListener(this.onFocusAutoClearHintListener);

		saveButton = (Button) findViewById(R.id.save_button);
		cancelButton = (ImageButton) findViewById(R.id.imageback);
		cancelButton.setClickable(true);
	}

	private void setListeners()
	{
		// 为saveButton 注册一个点击事件监听器
		saveButton.setOnClickListener(new View.OnClickListener()
		{
			// 当按钮被点击时调用该方法
			public void onClick(View v)
			{
				// addUser();
				int ecolor = Color.RED; // whatever color you want
				String estring = "";
				String name = username.getText().toString().trim();
				String passd = password.getText().toString().trim();
				String moblie = phoneno.getText().toString().trim();
				String repassd = repassword.getText().toString().trim();
				ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);

				if (name.length() == 0)
				{
					estring = "用户名不能为空";
					SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
					ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
					username.setError(ssbuilder);
					return;
				}
				else if (moblie.length() == 0)
				{
					estring = "手机号不能为空";
					SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
					ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
					phoneno.setError(ssbuilder);
					return;
				}
				else if (passd.length() == 0)
				{
					estring = "密码不能为空";
					SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
					ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
					password.setError(ssbuilder);
					return;
				}
				else if (repassd.length() == 0)
				{
					estring = "确认密码不能为空";
					SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
					ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
					repassword.setError(ssbuilder);
					return;
				}
				else if (!(repassd.toString()).equals(passd.toString()))
				{
					estring = "密码不一致";
					SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
					ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
					repassword.setError(ssbuilder);
					return;
				}
				new Thread(new Login()).start();
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener()
		{
			// 当按钮被点击时调用该方法
			public void onClick(View v)
			{
				oThis.onBackPressed();
			}
		});
	}

	class Login implements Runnable
	{

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			addUser();
			Looper.loop();
		}

	}

	// @Override
	// public boolean onTouchEvent(MotionEvent event)
	// {
	// // TODO Auto-generated method stub
	// if (event.getAction() == MotionEvent.ACTION_DOWN)
	// {
	// if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() !=
	// null)
	// {
	// manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
	// InputMethodManager.HIDE_NOT_ALWAYS);
	// }
	// }
	// return super.onTouchEvent(event);
	// }

	// public static OnFocusChangeListener onFocusAutoClearHintListener = new
	// OnFocusChangeListener()
	// {
	// @Override
	// public void onFocusChange(View v, boolean hasFocus)
	// {
	// EditText textView = (EditText) v;
	// String hint;
	// if (hasFocus)
	// {
	// hint = textView.getHint().toString();
	// textView.setTag(hint);
	// textView.setHint("");
	// }
	// else
	// {
	// hint = textView.getTag().toString();
	// textView.setHint(hint);
	// }
	// }
	// };

	/**
	 * 拼写检测，检测输入内容是否合乎要求
	 */
	public void addUser()
	{
		
			proDialog = ProgressDialog.show(oThis, "", "Loading...", true, true);

			String registerInfo = registerUser();
			if (registerInfo.equals("SAVE_SUCCESS"))
			{
//				oThis.onBackPressed();
				 Toast.makeText(oThis, "修改成功", Toast.LENGTH_SHORT).show();
				// // 到下一页面
				// Intent intent = new Intent();
				// intent.setClass(Register.this, Login.class);
				// startActivity(intent);
			}
			else if (registerInfo.equals("SAVE_NOTSUCCESS"))
			{
				Toast.makeText(oThis, "修改失败", Toast.LENGTH_SHORT).show();
			}
			else if (registerInfo.equals("LOGIN_PASSWORD_ERROR"))
			{
				Toast.makeText(oThis, "原密码错误", Toast.LENGTH_SHORT).show();
			}
			proDialog.dismiss();
	}

	/**
	 * 注册用户
	 */
	public String registerUser()
	{
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username.getText().toString().trim()));
		params.add(new BasicNameValuePair("oldpassword", oldpassword.getText().toString().trim()));
		params.add(new BasicNameValuePair("password", password.getText().toString().trim()));
		params.add(new BasicNameValuePair("phoneno", phoneno.getText().toString().trim()));

		JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.URLMODIFYUSER, params);
		String registerInfo = "SAVE_NOTSUCCESS";
		if (res != null)
		{
			try
			{
				registerInfo = res.get("registerInfo").toString();
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return registerInfo;
	}

	class InitUser implements Runnable
	{

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			initUser();
			Looper.loop();
		}

	}

	public void initUser()
	{
		Message message = myHandler.obtainMessage();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", myApplication.getAccount()));
		JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.URLFINDUSER, params);
		Map<String, String> map = new HashMap<String, String>();
		if (res != null)
		{
			try
			{
				if (StringUtil.isNotEmpty(res.get("phoneno").toString()))
				{
					map.put("username", myApplication.getAccount());
					map.put("phoneno", res.get("phoneno").toString());
					message.obj = map;
					message.what = LOADUSERSUCC;
				}
				else
				{
					message.what = LOADUSERERR;
				}
				myHandler.sendMessage(message);
				// username.setText(myApplication.getAccount());
				// if (StringUtil.isNotEmpty(res.get("phoneno").toString()))
				// {
				// phoneno.setText(res.get("phoneno").toString());
				// }
				// else
				// {
				// phoneno.setText(myApplication.getSjh());
				// }
				// username.setEnabled(false);
				// phoneno.setEnabled(false);
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what)
			{
				case LOADUSERERR:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					username.setText(myApplication.getAccount());
					phoneno.setText(myApplication.getSjh());
					username.setEnabled(false);
					phoneno.setEnabled(false);
					break;
				case LOADUSERSUCC:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Map<String, Object> map = (Map<String, Object>) msg.obj;
					username.setText(map.get("username").toString());
					phoneno.setText(map.get("phoneno").toString());
					username.setEnabled(false);
					phoneno.setEnabled(false);
					break;
				default:
					break;
			}
		}
	};

}
